﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.Windows.Threading;
using System.ComponentModel;
using System.Windows.Data;
using System.Windows;
using System.IO;

//TODO: Log To File
namespace LAeMail.Infrastructure
{
    public enum LogLevel
    {
        Debug,
        Info,
        Warning,
        Error
    }

    public class LogItem
    {
        public DateTime Timestamp { get; set; }
        public String LogLevel { get; set; }
        public String Message { get; set; }
    }

    public class Logger
    {
        private const int MAX_LOGLIST = 200;

        private ObservableCollection<LogItem> logList { get; set; }
        private ICollectionView logCollectionView { get; set; }
        private Dispatcher dispatcher { get; set; }
        private bool logToFile { get;set; }

        public void SetLoggerList(ObservableCollection<LogItem> logList)
        {
            this.logList = logList;
            this.logCollectionView = CollectionViewSource.GetDefaultView(this.logList);
            this.dispatcher = Application.Current.Dispatcher;
        }

        public void SetLogToFile(bool logToFile)
        {
            this.logToFile = logToFile;
        }

        public void Log(LogLevel logLevel, string logMsg)
        {
            LogItem logItem = new LogItem()
            {
                LogLevel = logLevel.ToString(),
                Timestamp = DateTime.Now,
                Message = logMsg
            };

            if (logList != null)
            {
                if (dispatcher != null)
                    dispatcher.BeginInvoke(new Action(delegate() { logToList(logItem); }));
                else
                    logToList(logItem);
            }

            if (logToFile && logLevel == LogLevel.Error)
            {
                using (StreamWriter w = File.AppendText("log.txt"))
                {
                    w.WriteLine("{0} {1}: {2}", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString(), logMsg);
                    w.Close();
                }
            }
        }

        private void logToList(LogItem logItem)
        {
            if (logList.Count > MAX_LOGLIST)
                logList.RemoveAt(0);

            logList.Add(logItem);
            logCollectionView.MoveCurrentToLast();
        }
    }
}
